const util = require('../../utils/util.js')
const app = getApp()
Page({
  data: {
    wxUser: null,
    user: {
      phone: null,
      sex: null,
      birthday: null,
      height: null
    },
    sexArray: [
      {
        id: 2,
        name: '女'
      },
      {
        id: 1,
        name: '男'
      },
    ],
    heightArray: []
  },
  onLoad: function () {
    //设置身高数据源
    var heightArray = []
    for (var i = 140; i < 240; i++) {
      heightArray.push(i)
    }
    this.setData({ heightArray: heightArray })
    app.wxUserReadyCallback = res => {
      this.setData({ wxUser: app.globalData.wxUser })
    }
  },
  onShow: function () {
    //获取用户头像与昵称
    this.setData({ wxUser: app.globalData.wxUser })
    let user = wx.getStorageSync('user')
    console.log(user)
    if (user) {
      this.setData({ user: user })
    }
  },
  updateUserAttribute: function (data){
    this.setData({ user: { ...this.data.user, ...data } })
    wx.request({
      url: app.globalData.api_domain + 'min-pro/user/' + app.globalData.user.openid,
      method: 'PUT',
      data: {
        ...data
      },
      header: {
        'token': app.globalData.user.token // 默认值
      },
      success: (res) => {
        console.log("updateUserAttribute", res);
        if (res.statusCode == 200) {
          if (res.data.apistatus == 1) {
            let user = { ...app.globalData.user, ...res.data.result }
            app.globalData = { ...app.globalData, user: user }
            wx.setStorageSync('user', user)
          }
        }
      }
    })
  },
  bindUserPhoneChange: function (e) {
    console.log('bindUserPhoneChange', e)
    let data = { phone: e.detail.value }
    //TODO 调用接口更新数据
    this.updateUserAttribute(data)
  },
  bindUserSexChange: function (e) {
    console.log('bindUserSexChange', e)
    let data = { sex: this.data.sexArray[e.detail.value].id }
    //TODO 调用接口更新数据
    this.updateUserAttribute(data)
  },
  bindUserBirthdayChange: function (e) {
    console.log('bindUserBirthdayChange', e)
    let data = { birthday: e.detail.value }
    //TODO 调用接口更新数据
    this.updateUserAttribute(data)
  },
  bindUserHeightChange: function (e) {
    console.log('bindUserHeightChange', e)
    let data = { height: this.data.heightArray[e.detail.value] }
    //TODO 调用接口更新数据
    this.updateUserAttribute(data)
  }
})
